using System;
using System.Resources;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using newtelligence.DasBlog.Runtime;
using newtelligence.DasBlog.Web.Core;

namespace newtelligence.DasBlog.Web
{
	public class ArchivesControl : UserControl
    {
        protected PlaceHolder contentPlaceHolder;
        private SharedBasePage requestPage;
		
        public ArchivesControl()
        {
        }
		
		private const int MAXCONTENTLEN = 100;
		private string TruncateDotDotDot(string content)
		{
			string retVal = StripAllTags(content); //Important to strip tags FIRST or we could truncate in the middle of a TAG, rather than in the middle of content.
			if (retVal.Length > MAXCONTENTLEN)
				retVal = retVal.Substring(0, Math.Min(MAXCONTENTLEN, retVal.Length)) + "...";
			return retVal;
		}
		
		private string StripAllTags(string content)
		{
			string regex = "<(.|\n)+?>";
			System.Text.RegularExpressions.RegexOptions options = System.Text.RegularExpressions.RegexOptions.IgnoreCase;
			System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(regex, options);
			string retVal = content;
			try
			{
				retVal = reg.Replace(content, String.Empty);
			}
			catch
			{ //swallow anything that might go wrong
			}
			return retVal;
		}
		
        private void Page_Load(object sender, EventArgs e)
        {
        	requestPage = this.Page as SharedBasePage;
			
        	CategoryCacheEntryCollection catCache = requestPage.DataService.GetCategories();
            
            // Build the archive navigator
        	StringBuilder catNav = new StringBuilder();
            catNav.Append("<p>");
			
            foreach (CategoryCacheEntry cce in catCache)
            {
                catNav.AppendFormat("<a href=\"archives.aspx#{0}\">{0}</a> &#8226; ", cce.DisplayName);
            }

        	ResourceManager resmgr = ApplicationResourceTable.Get();;
			string none = resmgr.GetString("text_no_category");
			catNav.AppendFormat("<a href=\"archives.aspx#{0}\">{0}</a> &#8226; ", none);
            catNav.Append("</p>");
            contentPlaceHolder.Controls.Add(new LiteralControl(catNav.ToString()));
			
            foreach (CategoryCacheEntry categoryCacheEntry in catCache)
            {
                EntryCollection catEntries = requestPage.DataService.GetEntriesForCategory(categoryCacheEntry.Name, "");
				
				HyperLink catLink = new HyperLink();
				catLink.CssClass = "date";
				catLink.Text = String.Format("{0} ({1})", categoryCacheEntry.Name, catEntries.Count);
				catLink.NavigateUrl = Utils.GetCategoryViewUrl(requestPage.SiteConfig, categoryCacheEntry.Name);

				string anchor = String.Format("<a name=\"{0}\"></a>", categoryCacheEntry.DisplayName);
				contentPlaceHolder.Controls.Add(new LiteralControl(anchor));
				contentPlaceHolder.Controls.Add(catLink);

				contentPlaceHolder.Controls.Add(new LiteralControl("&nbsp;"));

				HyperLink rssLink = new HyperLink();
				rssLink.CssClass = "categoryListXmlLinkStyle";
				rssLink.NavigateUrl = Utils.GetRssCategoryUrl(requestPage.SiteConfig,categoryCacheEntry.Name);
				System.Web.UI.WebControls.Image rssImg = new System.Web.UI.WebControls.Image();
				rssImg.ImageUrl = requestPage.GetThemedImageUrl("rssButton");                        
				rssLink.Controls.Add(rssImg);
				contentPlaceHolder.Controls.Add(rssLink);

				contentPlaceHolder.Controls.Add(new LiteralControl("<hr size=\"1\">"));
                contentPlaceHolder.Controls.Add(new LiteralControl("<p>"));
				
                foreach (Entry entry in catEntries)
                {
                	contentPlaceHolder.Controls.Add(RenderCategory(entry));
                }
				
				contentPlaceHolder.Controls.Add(new LiteralControl("</p>"));
            }
			
			EntryCollection entries = requestPage.DataService.GetEntriesForDay(
				DateTime.MaxValue.AddDays(-2),
				TimeZone.CurrentTimeZone,
				String.Empty,
				int.MaxValue,
				int.MaxValue,
				String.Empty);

			HyperLink noneLink = new HyperLink();
			noneLink.CssClass = "date";
			noneLink.Text = String.Format("{0} ({1})", none, entries.Count);
			string anchorNone = String.Format("<a name=\"{0}\"></a>", none);
			contentPlaceHolder.Controls.Add(new LiteralControl(anchorNone));

			contentPlaceHolder.Controls.Add(noneLink);

			contentPlaceHolder.Controls.Add(noneLink);
			contentPlaceHolder.Controls.Add(new LiteralControl("&nbsp;"));

			
			contentPlaceHolder.Controls.Add(new LiteralControl("<hr size=\"1\">"));
			contentPlaceHolder.Controls.Add(new LiteralControl("<p>"));

			foreach (Entry entry in entries)
			{
				if (entry.Categories != null && entry.Categories.Length == 0)
				{
					contentPlaceHolder.Controls.Add(RenderCategory(entry));
				}
			}
			
			contentPlaceHolder.Controls.Add(new LiteralControl("</p>"));
			
            DataBind();
        }

		private PlaceHolder RenderCategory(Entry entry)
		{
			PlaceHolder placeHolder = new PlaceHolder();

			if (entry.IsPublic == true)
			{
				if (requestPage.SiteConfig.AdjustDisplayTimeZone)
				{
					newtelligence.DasBlog.Util.WindowsTimeZone tz = requestPage.SiteConfig.GetConfiguredTimeZone();
					DateTime localTime = tz.ToLocalTime(entry.CreatedUtc);
					
					placeHolder.Controls.Add(
						new LiteralControl(localTime.ToString("yyyy-MM-dd hh:mm:ss tt") + " "));
				}
				else
				{
					placeHolder.Controls.Add(
						new LiteralControl(entry.CreatedUtc.ToString("yyyy-MM-dd hh:mm:ss tt") + " UTC "));
				}

				HyperLink hl = new HyperLink();
				if (entry.Link != null)
				{
					hl.NavigateUrl = entry.Link;
				}
				else
				{
					hl.NavigateUrl = Utils.GetPermaLinkUrl(entry);
				}
				hl.Text = entry.Title;
				hl.CssClass = "TitleLinkStyle";
				placeHolder.Controls.Add(hl);

				placeHolder.Controls.Add(new LiteralControl("<br/>"));
			}

			return placeHolder;
		}

		override protected void OnInit(EventArgs e)
        {
            InitializeComponent();
            base.OnInit(e);
        }
		
        private void InitializeComponent()
        {
            this.Load += new EventHandler(this.Page_Load);
        }
    }
}
